package com.example.programme.home;

import static android.content.ContentValues.TAG;



import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;



import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.programme.MyToast;
import com.example.programme.R;
import com.example.programme.Items.WordItem;
import com.example.programme.database.DBHelper;
import com.example.programme.database.DBManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import java.util.HashMap;



import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class WordSearchFragment extends Fragment implements View.OnClickListener {

    EditText editText;
    TextView textView;
    Handler handler;
    DBHelper dbHelper;
    String text ="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_wordsearch, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        editText = getActivity().findViewById(R.id.et);
        textView = getActivity().findViewById(R.id.tv);
        Button query = getActivity().findViewById(R.id.query);
        dbHelper = new DBHelper(getActivity());

        //开启
        handler = new Handler(Looper.myLooper()) {

            @Override
            public void handleMessage(@NonNull Message msg){
                super.handleMessage(msg);
                HashMap<String,String> map =( HashMap<String,String>) msg.obj;

                text=map.get("text");//原文
                String cixing="译文:";
                String translation=map.get("translation");//译文
                String result="原文："+"\n        "+text+"\n"+cixing+"  "+"\n        "+translation;
                textView.setText(result);

                    Button collecttion =getActivity().findViewById(R.id.collecttion);
                    if(!text.isEmpty()) collecttion.setVisibility(View.VISIBLE);
                    collecttion.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                Collection(text,cixing,translation);//收藏
                        }
                    });


            }

        };


        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String word = editText.getText().toString();
                //调用上网查词方法
                if(!word.isEmpty())
                queryWord(word);
                else MyToast.makeText(getActivity(),"请输入要翻译的文本",Toast.LENGTH_LONG);

            }
        });
        //词库中搜索
        Button search1=getActivity().findViewById(R.id.search1);
        search1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = editText.getText().toString().trim();
                DBManager dbManager = new DBManager(getActivity());
                boolean flag = false;
                if (!TextUtils.isEmpty(str)) {
                    if (dbManager.listAll() != null) {
                        for (WordItem word : dbManager.listAll()) {//获取数据库中的单词
                            if (word.getEnglish().equals(str)) {
                                textView.setText("查询文本：" + word.getEnglish() + "\n" + "查询结果：" + word.getChinese());
                                MyToast.makeText(getActivity(), "查找成功", Toast.LENGTH_SHORT);
                                flag = true;
                            }
                        }
                        if (flag == false)
                            MyToast.makeText(getActivity(), "没找到相关信息", Toast.LENGTH_SHORT);
                    } else MyToast.makeText(getActivity(), "没找到相关信息", Toast.LENGTH_SHORT);
                } else
                    MyToast.makeText(getActivity(), "请输入要查找的信息",Toast.LENGTH_SHORT);
            }
        });


    }


    /**
     * 收藏文本
     *
     */
    private void Collection(String english,String cixing ,String chinese) {
        if (!TextUtils.isEmpty(english) && !TextUtils.isEmpty(chinese)) {
            boolean flag1=false;
            DBManager dbManager = new DBManager(getActivity());
            if (dbManager.listAll() != null) {//调用方法获取数据库中的单词
                for (WordItem word : dbManager.listAll()) {

                    if (word.getEnglish().equals(english) ) {
                        flag1=true;//有重复的数据
                    }
                }
                //添加新数据
                if(flag1==false){
                    dbManager.add(english,cixing,chinese);
                    MyToast.makeText(getActivity(), "收藏成功", Toast.LENGTH_LONG);
                }
                //更新重复的数据
                else {
                    dbManager.update(english,cixing,chinese);
                    MyToast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT);
                }
            }
            else dbManager.add(english,cixing,chinese);
            //将新添加书的单词更新在列表中显示
        }else {MyToast.makeText(getActivity(),"无可收藏信息",Toast.LENGTH_LONG);
        }
    }
    /**
     * 实现上网查词
     1.创建OkClient和Request对象
     2.创建Call对象
     3.重写Call对象的enqueue方法
       1.获取响应数据
       2.封装成json对象
       3.读取信息
       4.发送message给handler
     * @param s 要查询的单词
     */
    public void queryWord(String s){
        String url =
                "https://fanyi.youdao.com/translate?doctype=json&i="+s;

        //1.创建OkClient和Request对象
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        //2.创建Call对象
        Call call = okHttpClient.newCall(request);
        //3.重写Call对象的enqueue方法
        call.enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //1.获取响应数据
                String str= response.body().string() ;//转成字符串
                Log.d(TAG, "onResponse: " + str);
                try {
                    //2.封装成json对象
                    JSONObject jsonObject1 = new JSONObject(str);
                    //3.读取信息
                    JSONArray jsonArray1= jsonObject1.optJSONArray("translateResult");
                    JSONArray jsonArray2 = jsonArray1.getJSONArray(0);
                  //  JSONArray str4=str3.optJSONArray(0);
                     String str1=jsonArray2.optString(0);
                    JSONObject str2=new  JSONObject(str1);

                    String str3=str2.optString("src");
                    String str4=str2.optString("tgt");

//
                    //4.创建message,包裹信息
                    Message message = new Message();
                    HashMap<String,String> map =new HashMap<String,String>();
                    map.put("text",str3);
                    map.put("translation",str4);
                    message.obj = map;
                    //5.发送message给handler
                    //获取msg对象，用于返回主线程

                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onClick(View view) {

    }
}
